package kr.co.dayve.site.management.service;


import kr.co.dayve.site.domain.*;
import kr.co.dayve.site.management.dao.*;
import org.springframework.web.multipart.MultipartFile;

import javax.imageio.ImageIO;
import javax.swing.*;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.awt.image.PixelGrabber;
import java.io.*;
import java.util.List;
import java.util.UUID;


public class PhotoBoardServiceImpl implements PhotoBoardService{

    public List getBoardListBySearchword(PhotoBoard photoBoard) {
        return photoBoardDao.getBoardListBySearchword(photoBoard);
    }

    public List getBoardListByNo(PhotoBoard photoBoard){
        return photoBoardDao.getBoardListByNo(photoBoard);
    }

    public String getTotalCountBySearchword(PhotoBoard photoBoard) {
        return photoBoardDao.getTotalCountBySearchword(photoBoard);
    }

    public String getTotalCountByNo(PhotoBoard photoBoard) {
        return photoBoardDao.getTotalCountBySearchword(photoBoard);
    }

    public String writeBoard(PhotoBoard board){
        return photoBoardDao.writeBoard(board);
    }

    public String updateBoard(PhotoBoard board){
        return photoBoardDao.updateBoard(board);
    }

    public String deleteBoard(PhotoBoard board){
        return photoBoardDao.deleteBoard(board);
    }

    public PhotoBoard getBoardByNo(String photo_board_no){
        return photoBoardDao.getBoardByNo(photo_board_no);
    }

    public String updateReplyCount(PhotoBoard board){
        return photoBoardDao.updateReplyCount(board);
    }

    public String updateHitCount(PhotoBoard board){
        return photoBoardDao.updateHitCount(board);
    }

    public String updateVoteCount(PhotoBoard board){
        return photoBoardDao.updateVoteCount(board);
    }

    public String updateNegativeCount(PhotoBoard board){
        return photoBoardDao.updateNegativeCount(board);
    }

    public String updateReportCount(PhotoBoard board){
        return photoBoardDao.updateReportCount(board);
    }

    /**
     * 파일 업로드 서비스
     * @param file
     * @param realPath
     * @return
     */
    public DayveFile uploadFile(MultipartFile file, String realPath){

        InputStream stream; // Input Stream 생성

        UUID uuid = UUID.randomUUID(); // 랜덤 UUID 이름 생성
        String tempFileName = uuid.toString(); // 임시 파일 이름 저장

        try {
            stream = file.getInputStream();

            OutputStream bos = new FileOutputStream(realPath + tempFileName);
            int bytesRead = 0;
            byte[] buffer = new byte[8192];
            while ((bytesRead = stream.read(buffer, 0, 8192)) != -1) {
                bos.write(buffer, 0, bytesRead);
            }
            bos.close();
            stream.close();

            // 파일 쓰고 stream 닫기

            /*
            if (logger.isDebugEnabled()) {
                logger.debug("The file has been written to \"" + realPath
                        + tempFileName);
            }
            */

        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

        DayveFile boardFile = new DayveFile();
        boardFile.setFileName(file.getOriginalFilename());
        boardFile.setFileSize(Long.toString(file.getSize()));
        boardFile.setContentType(file.getContentType());
        boardFile.setTempFileName(tempFileName);

        return boardFile;
    }

    /**
     * 썸네일 생성 서비스
     * @param src
     * @param dest
     * @param width
     * @param height
     * @return
     * @throws IOException
     */
    public String createThumbnail(File src, File dest, int width, int height) throws IOException{
        final int RATIO = 0;
        final int SAME = -1;

        Image srcImg = null;
        String suffix = src.getName().substring(src.getName().lastIndexOf('.')+1).toLowerCase();
        if (suffix.equals("bmp") || suffix.equals("png") || suffix.equals("gif")) {
            srcImg = ImageIO.read(src);
        } else {
            // BMP가 아닌 경우 ImageIcon을 활용해서 Image 생성
            // 이렇게 하는 이유는 getScaledInstance를 통해 구한 이미지를
            // PixelGrabber.grabPixels로 리사이즈 할때
            // 빠르게 처리하기 위함이다.
            srcImg = new ImageIcon(src.toURL()).getImage();
        }

        int srcWidth = srcImg.getWidth(null);
        int srcHeight = srcImg.getHeight(null);

        int destWidth = -1, destHeight = -1;

        if (width == SAME) {
            destWidth = srcWidth;
        } else if (width > 0) {
            destWidth = width;
        }

        if (height == SAME) {
            destHeight = srcHeight;
        } else if (height > 0) {
            destHeight = height;
        }

        if (width == RATIO && height == RATIO) {
            destWidth = srcWidth;
            destHeight = srcHeight;
        } else if (width == RATIO) {
            double ratio = ((double)destHeight) / ((double)srcHeight);
            destWidth = (int)((double)srcWidth * ratio);
        } else if (height == RATIO) {
            double ratio = ((double)destWidth) / ((double)srcWidth);
            destHeight = (int)((double)srcHeight * ratio);
        }

        Image imgTarget = srcImg.getScaledInstance(destWidth, destHeight, Image.SCALE_SMOOTH);
        int pixels[] = new int[destWidth * destHeight];
        PixelGrabber pg = new PixelGrabber(imgTarget, 0, 0, destWidth, destHeight, pixels, 0, destWidth);
        try {
            pg.grabPixels();
        } catch (InterruptedException e) {
            throw new IOException(e.getMessage());
        }
        BufferedImage destImg = new BufferedImage(destWidth, destHeight, BufferedImage.TYPE_INT_RGB);
        destImg.setRGB(0, 0, destWidth, destHeight, pixels, 0, destWidth);

        ImageIO.write(destImg, "jpg", dest);


        return dest.getName();
    }

   /**
     * 갤러리 추천 중복 체크
     * @param vote
     * @return
     */
    public String checkDuplicateVote(Vote vote) {
        return photoBoardDao.checkDuplicateVote(vote);
    }

    /**
     * 갤러리 추천 등록
     * @param vote
     * @return
     */
    public String insertVoterToList(Vote vote) {
        return photoBoardDao.insertVoterToList(vote);
    }

    /**
     * 갤러리 신고
     * @param report
     * @return
     */
    public String photoBoardReport(Report report) {
        return photoBoardDao.photoBoardReport(report);
    }

    /**
     * 갤러기 신고 중복 체크
     * @param report
     * @return
     */
    public String checkDuplicateReport(Report report) {
        return photoBoardDao.checkDuplicateReport(report);
    }

    /**
     * 갤러리 업데이트. (사진 제외)
     * @param board
     * @return
     */
    public String updateBoardNotImage(PhotoBoard board) {
        return photoBoardDao.updateBoardNotImage(board);
    }

    ///////////////////////////////////////
    // Spring Framework Setter Injection //
    ///////////////////////////////////////

    private MemberDao memberDao;
    private PhotoBoardDao photoBoardDao;

    public void setMemberDao(MemberDaoImpl memberDao) {
        this.memberDao = memberDao;
    }

    public void setPhotoBoardDao(PhotoBoardDao photoBoardDao) {
        this.photoBoardDao = photoBoardDao;
    }
}
